<template>
	<div class="matchmaker">
    <header class="header">
      <div class="city" @click="state.areaShow = true">
        <van-icon color="#555555" name="location" size="16" />
        <span style="font-size: 16px">{{ state.pageInfo.city || '全部' }}</span>
        <van-icon class="play" color="#a5a5a5" name="play" size="12" />
      </div>
      <div class="tabs">
        <van-tabs
            v-model:active="state.active"
            line-width="30px"
            title-inactive-color="#A6A6A6"
            title-active-color="#333333"
            :before-change="tabsBeforeChange"
        >
          <van-tab v-for="item of state.tabs" :name="item" :title="item" />
        </van-tabs>
      </div>
      <div>
<!--        <van-dropdown-menu active-color="#f54386">-->
<!--          <van-dropdown-item-->
<!--              title="性别筛选"-->
<!--              v-model="state.pageInfo.sex"-->
<!--              :options="state.sexOption"-->
<!--              @change="sexMenuChange"-->
<!--          />-->
<!--        </van-dropdown-menu>-->
      </div>
    </header>
		<main class="my_swiper_box">
			<swiper
				class="my_swiper"
				direction="vertical"
				:spaceBetween="15"
				:modules="[Virtual]"
				virtual
				@slideChange="onSlideChange"
			>
				<template v-for="(item, index) of state.menberList" :key="item.id">
					<swiper-slide class="swipe_item">
						<!-- 视频 -->
						<MyVideoPlay3
							v-if="item.is_red_mother_video && item.red_mother_vcr.video_url"
							:ref="(el) => setItemRef(el, item.id)"
							:item="item"
              :page="state.module"
							@videoClick="videoClick(item.user_id)"
						/>
						<!-- 图片 -->
						<img class="img" v-else v-lazy="imgUrl + item.user_img" />

						<!-- 用户信息 -->
						<div class="user_info">
							<div>
								<span>{{ item.username }}</span> <span>{{ item.age }}岁</span>
								<img v-if="showVip(item)" class="vip" src="@/assets/img/vip_icon.png" />
								<img v-if="item.is_red_mother_video" class="certification" src="@/assets/img/certification_icon.png" />
							</div>
							<p>{{ item.province }} {{ item.city }}</p>
						</div>
						<!-- 头像 -->
						<van-image
							class="avatar"
							round
							width="45px"
							height="45px"
							fit="cover"
							:src="getUserHeadImg(item)"
							@click="avatarClick(item.user_id)"
						/>

						<!-- 收藏 -->
						<div class="share collection" v-debounce="() => collect(item.user_id, index)">
							<img v-if="item.is_collect" src="@/assets/img/video/collectionActive_icon.png" />
							<img v-else src="@/assets/img/video/collection_icon.png" />
							<span>{{ item.like_num }}</span>
						</div>
						<!-- 分享 -->
						<div class="share" @click="state.codeDialogShow = true">
							<img src="@/assets/img/video/share_icon.png" />
							<span>{{ item.share_num }}</span>
						</div>
						<!-- 电话 -->
						<a class="tel" :href="state.mobile" v-debounce="() => callMobile(item.mobile)">
							<img src="@/assets/img/tel_icon.png" />
						</a>
            <span class="tel_bottom_text">牵线</span>
					</swiper-slide>
				</template>
			</swiper>
		</main>
		<MyTabbar />

		<!-- 成为红娘弹窗 -->
		<MyDialogBtn v-model:show="state.becomeMatchmakerShow">
			<template #content>
				<div style="max-height: 50vh; overflow: scroll">
					<div style="margin-bottom: 20px;text-align: center">是否想成为红娘？</div>
          <div style="font-weight: bold;color: #f6438a;margin-bottom: 10px;">红娘权益</div>
					<p style="font-size: 16px; text-align: left; line-height: 24px" v-html="state.matchmaker_introduce"></p>
				</div>
			</template>
			<template #btn>
				<van-button type="primary" @click="jumpMatchmaker">去了解</van-button>
				<van-button type="success" @click="state.becomeMatchmakerShow = false">再看看</van-button>
			</template>
		</MyDialogBtn>

    <!-- 分享说明 -->
    <MyDialogBtn v-model:show="state.codeDialogShow" column>
      <template #content>
        <div style="max-height: 50vh; overflow: scroll">
          <div style="margin-bottom: 30px">分享说明</div>
          <p v-html="state.promote_contents" style="font-size: 13px; text-align: left; line-height: 24px"></p>
        </div>
      </template>
      <template #btn>
        <van-button type="primary" @click="state.codeDialogShow = false">确定</van-button>
      </template>
    </MyDialogBtn>

    <van-popup v-model:show="state.areaShow" round position="bottom">
      <van-area :area-list="areaList" :value="state.areaDefaultCode" columns-num="2" @confirm="areaConfirm" @cancel="state.areaShow = false" />
    </van-popup>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, onActivated } from 'vue';
import type { ComponentPublicInstance } from 'vue';
import {useRouter, useRoute} from 'vue-router';
import { Virtual } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import type { Swiper as SwiperClass } from 'swiper/types';
import {globalConfigValue, getAddressByGPS, getWxConfig} from '@/api/common';
import {memberList, saveCollect, updateShareCount} from '@/api/index';

import { useMainStore } from '@/store';
import wxApiReady from '@/hooks/wxApiReady';
import showVip from '@/hooks/showVip';

import MyTabbar from '@/components/MyTabbar.vue';
import MyVideoPlay3 from '@/components/MyVideoPlay3.vue';
import MyDialogBtn from '@/components/MyDialogBtn.vue';
import {AreaColumnOption, DropdownItemOption, Toast} from 'vant';
import wx from 'weixin-jsapi';
import {areaList} from "@vant/area-data";

const imgUrl = import.meta.env.VITE_IMG_URL;
const siteTitle = import.meta.env.VITE_SITE_TITLE;
const siteDomain = import.meta.env.VITE_DOMAIN;
const mainStore = useMainStore();
const router = useRouter();
const route = useRoute();
const state = reactive<any>({
  module:'red_mother',//红娘
	showFlag: true,
  areaShow: false,
  areaDefaultCode: '110101',
	becomeMatchmakerShow: false,
  codeDialogShow: false,
  promote_contents:'点击右上角【...】分享到朋友圈或微信群',
	mobile: 'javascript:;',
	pageInfo: {
		pageIndex: 1,
		pageSize: 50,
		user_id: mainStore.user_id,
		state: 3,
    city: null,
    share_user_id: route.query.share_user_id || '',
    sex: ''
	},
  sexOption: [
    { text: '查看全部', value: '' },
    { text: '只看男性', value: '男' },
    { text: '只看女性', value: '女' }
  ],
  payShow: false,
  vipShow: false,
  active: 0,
  tabs: ['全部', '同城'],
  currentIndex: 0,
	menberList: [] as any[],

	matchmaker_introduce: '',

  province: '',
  city: '',
  country: ''
});
onMounted(() => {
	getGlobalConfigValue();
});

onActivated(() => {
  if (state.menberList.length == 0) {
    state.pageInfo.user_id = mainStore.user_id;
    state.pageInfo.pageIndex = 1;
    state.menberList = [];
    getMemberList();
  } else {
    if (!mainStore.isUserDetailPath) {
      state.pageInfo.user_id = mainStore.user_id;
      state.pageInfo.pageIndex = 1;
      state.menberList = [];
      getMemberList();
    }
  }
});

// 跳转红娘认证页面
const jumpMatchmaker = () => {
  state.becomeMatchmakerShow = false;
  router.push({ name: 'becomeMatchmaker' })
}

// 获取用户头像
const getUserHeadImg = (item:any) : string => {
  if (!item.head_img_url) {
    if (!item.user_img) {
      return imgUrl + item.user_img
    }
    return imgUrl + item.photo_list[0]
  } else {
    return item.head_img_url
  }
}

// 性别筛选
const sexMenuChange = (value: DropdownItemOption) => {
  state.pageInfo.pageIndex = 1;
  state.menberList = [];
  getMemberListBuyCity();
};

// 定位城市获取列表
const getMemberListBuyCity = (): Promise<void> => {
  Toast.loading({
    message: '正在定位城市',
    forbidClick: true,
  });
  state.pageInfo.pageIndex = 1;
  state.menberList = [];
  return new Promise<void>((resolve, reject) => {
    // 获取城市
    wxApiReady(['getLocation'])
        .then((res) => {
          wx.getLocation({
            type: 'wgs84',
            success: async (res: any) => {
              const { latitude, longitude } = res;
              const addressRes = await getAddressByGPS(latitude, longitude);
              const { city, district, province } = addressRes.data.result.address_component;
              state.city = city;
              state.province = province;
              state.country = district;
              state.pageInfo.city = city;
              state.active = '同城';
              // 设置选择器默认城市
              const city_list: any = areaList.city_list;
              state.areaDefaultCode = Object.keys(city_list).find((key) => {
                return city_list[key] === city;
              });
              await getMemberList();
              resolve();
            },
            complete: (res: any) => {
            }
          });
        })
        .catch((err: Error) => {
          console.log('err', err)
        });
  });
};

// 视频点击
const videoClick = async (like_user_id: number) => {
	iframeRefs[currentItem.value.id].play();
};

// 头像点击
const avatarClick = (user_id: number): void => {
	router.push({ name: 'userDetail', query: { user_id, type: 'matchmaker' } });
};

// 收藏/取消收藏
const collect = async (like_user_id: number, index: number): Promise<any> => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('您的资料审核未通过');
  } else {
    if (!mainStore.userInfo.identity || mainStore.userInfo.identity == 0) {
      router.push('registered');
      return;
    }
  }
	const res = await saveCollect(mainStore.user_id, like_user_id);
	Toast(res.errorInfo);
	const { is_collect, like_num } = state.menberList[index];
	const isCollect: boolean = res.data !== 1 ? false : true;
	state.menberList[index].is_collect = isCollect ? 0 : 1;
	state.menberList[index].like_num = isCollect ? like_num - 1 : like_num + 1;
};

// 分享
const initShare = async (update:boolean = false) => {
	const wxConfig = mainStore.wxConfig;
  console.log('wxConfig：',wxConfig)
  if (wxConfig == null || update) {
    const configRes = await getWxConfig();
    mainStore.wxConfig = configRes.data;
  }
  const { appId, timestamp, nonceStr, signature } = mainStore.wxConfig;
  let jsApiList = ['onMenuShareAppMessage', 'onMenuShareTimeline'];
  wx.config({
    debug: false,
    appId,
    timestamp,
    nonceStr,
    signature,
    jsApiList
  });
  wx.ready(() => {
    		wx.onMenuShareAppMessage({
    			title: siteTitle, // 分享标题
    			desc: `我是【${currentItem.value.username}】，实名相亲，为您牵线。`, // 分享描述
    			link: `https://ztcy.huimaibuy.com/h5/#/userDetail?parent_id=${mainStore.user_id}&user_id=${currentItem.value.user_id}&type=matchmaker&share_user_id=${mainStore.user_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
    			imgUrl: currentItem.value.head_img_url, // 分享图标
    			type: 'link', // 分享类型,music、video或link，不填默认为link
    			dataUrl: '', // 如果 type 是music或video，则要提供数据链接，默认为空
    			success: async () => {
    				// 用户点击了分享后执行的回调函数
    				// 更新转发数量
    				const res = await updateShareCount(currentItem.value.user_id);
    				console.log(res);
    			},
    			cancel: (res: any) => {
    				console.log(res);
    			}
    		});
    		wx.onMenuShareTimeline({
    			title: siteTitle, // 分享标题
    			link: `https://ztcy.huimaibuy.com/h5/#/userDetail?parent_id=${mainStore.user_id}&user_id=${currentItem.value.user_id}&type=matchmaker&share_user_id=${mainStore.user_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
    			imgUrl: currentItem.value.head_img_url, // 分享图标
    			success: async () => {
    				// 用户点击了分享后执行的回调函数
    				// 更新转发数量
    				const res = await updateShareCount(currentItem.value.user_id);
    				console.log(res);
    			},
    			cancel: (res: any) => {
    				console.log(res);
    			}
    		});
  });
  wx.error((res:any) => {
    console.log('err', res)
  });
};

// 拨打电话
const callMobile = (mobile: string): any => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('您的资料审核未通过');
  }
  if (!mainStore.userInfo.state || mainStore.userInfo.state == 0) {
    return Toast('成为平台会员后可查看联系方式');
  } else {
	  state.mobile = `tel:${mobile}`;
  }
};

const checkRoles = (key: string): boolean => {
  return String(mainStore.userInfo?.state).split(',').includes(key);
};

// 视频组件dom列表
interface IIframeRefs {
	[key: number | string]: any;
}
const iframeRefs: IIframeRefs = {};
const setItemRef = (el: Element | ComponentPublicInstance | null, key: number | string) => {
	if (el) {
		iframeRefs[key] = el;
	}
};

// 当前元素
const currentItem = computed<any>(() => state.menberList[state.currentIndex]);

// swiper 切换
let oldSwiperIndex = ref<number>(0);

let timer: NodeJS.Timeout | null = null;
const onSlideChange = (e: SwiperClass) => {
	if (timer) {
		clearTimeout(timer);
		timer = null;
	}
	timer = setTimeout(() => {
		if (e.activeIndex >= 2 && state.showFlag) {
		  if (!checkRoles('3')) {//当前用户是否开通红娘
			  state.becomeMatchmakerShow = true;
      }
			state.showFlag = false;
		}
		// 加载更多
		if (e.activeIndex + 1 == state.menberList.length) {
			getMemberList();
		}
    console.log('currentItem',currentItem)
		state.currentIndex = e.activeIndex;
		// 重新加载当前视频
		if (currentItem.value && currentItem.value?.red_mother_vcr.video_url) {
			nextTick(() => {
				iframeRefs[currentItem.value.id].videoRef.load();
			});
		}

		// 暂停上条视频
		const pvreItem = state.menberList[oldSwiperIndex.value];
		if (pvreItem && pvreItem.red_mother_vcr.video_url) {
			nextTick(() => {
				iframeRefs[pvreItem.id].videoRef.pause();
			});
		}
		oldSwiperIndex.value = e.activeIndex;
		initShare();
	}, 500);
};

// 获取用户列表
const getMemberList = async () => {
  Toast.loading({
    message: '正在加载中',
    forbidClick: true,
  });
	const res = await memberList(state.pageInfo);
	if (res.data.dataList.length) {
		state.menberList = [...state.menberList, ...res.data.dataList];
		state.pageInfo.pageIndex++;
		await initShare(false);
	}
};

// 红娘介绍文字
const getGlobalConfigValue = async () => {
  const matchmakerIntroduce = mainStore.matchmakerIntroduce;
  if (matchmakerIntroduce == null) {
    const res = await globalConfigValue('matchmaker_introduce');
    state.matchmaker_introduce = res.data.item_value;
    mainStore.matchmakerIntroduce = res.data.item_value;
  } else {
    state.matchmaker_introduce = matchmakerIntroduce;
  }
};

// 选择城市确认
const areaConfirm = (result: AreaColumnOption[]) => {
  state.pageInfo.pageIndex = 1;
  state.menberList = [];
  state.pageInfo.city = result[1].name;
  getMemberList();
  state.active = '同城';
  state.areaShow = false;
};

// tab切换
const tabsBeforeChange = (name: number | string): boolean => {
  state.pageInfo.pageIndex = 1;
  state.menberList = [];
  if (name === '全部') {
    state.pageInfo.city = '';
    getMemberList();
  } else if (name === '同城') {
    getMemberListBuyCity();
  } else {
    getMemberList();
  }
  state.currentIndex = 0;
  oldSwiperIndex.value = 0;
  return true;
};
</script>

<style lang="scss" scoped>
:deep(.my_dialog_btn) {
  main {
    width: 285px;
    text-align: unset;
    .content_box {
      padding: 30px;
    }
  }
}

:deep(.van-tabs) {
  width: 100%;
  .van-tabs__wrap {
    height: 50px !important;
    .van-tabs__nav {
      justify-content: space-between;
      .van-tab {
        flex: auto;
        padding: 0;
        font-size: 16px;
      }
      .van-tab--active {
        font-size: 17px;
        font-weight: bold;
      }
    }

    .van-tabs__line {
      bottom: 20px;
      background: #f6438a;
    }
  }
}

:deep(.van-dropdown-menu) {
  .van-dropdown-menu__bar {
    box-shadow: none;
    background: white;
    .van-dropdown-menu__title {
      color: #f54386;
      font-size: 13px;
      &::after {
        border-color: transparent transparent #f54386 #f54386;
      }
    }
  }
  .van-popup--top {
    border-radius: 0 0 15px 15px;
  }
}
.matchmaker {
	padding: 0 15px;
  .header {
    @include flx-justify-between;
    height: 60px;
    .city {
      @include flx-align-center;
      height: 100%;
      span {
        font-size: 13px;
        margin-left: 2px;
      }
      .play {
        transform: rotate(90deg);
      }
    }
    .tabs {
      @include flx-center;
      height: 100%;
      width: 190px;
    }
  }
	.my_swiper_box {
		.my_swiper {
			//height: calc(100vh - 80px - env(safe-area-inset-bottom));
		}
		.swipe_item {
			.img {
				height: calc(100vh - 80px - env(safe-area-inset-bottom));
			}
		}
	}
}
</style>
